var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var base64 = require('../../utils/Base64');
var app = getApp();

Page({
  data: {
    util: util,
    isIphone_x: false,
    screen_w: 320,
    screen_h: 480,
    info_item_w: 290,
    input_w: 240,
    sexValue: '',
    isAccept: true,
    photoArr: [],
    photo_w: 90,
    photo_h: 135,
    videoArr: [],
    video_w: 140,
    video_h: 92,
    userInfo: "",
    avatarurl: "",
    businessInfo: "",
    showAuthView: false,

    hasBaseInfo: false,
    hasPhoto: false,
    hasVideo: false,
    hasApp: false,

    showVideo: false,
    autoReply: false
  },

  cuid: 0,
  token: '',
  openid: '',
  user_name: '',
  user_sex: '',
  user_age: '',
  user_intro: '',
  newAvatarUrl: '',
  user_reply: '',

  isReadedXieyi: false,

  onLoad: function (data) {
    var that = this
    app.getWxCheck(function(show) {
      that.setData({
        showVideo: show
      })
    })
    
  },

  getLoginUserInfo (reget = false) {
    tt.showLoading({
      title: 'loading...',
      mask: "true"
    });
    var that = this
    app.LoginUserInfo(function(res){
      console.log("用户信息", res);

      if(res && res != '-1' && res != '-2'){
        that.cuid = res.uid
        that.token = res.token
        that.openid = res.openid
        
        let avatarLink = res.avatar ? res.avatar : '/images/default_ava.jpg'
        if (that.newAvatarUrl && that.newAvatarUrl.length > 0) {
          avatarLink = that.newAvatarUrl
        }
        if (that.user_name && that.user_name.length > 0) {
          res.uname = that.user_name
        }
        if (that.user_sex && that.user_sex >= 0) {
          res.sex = that.user_sex
        } else if (!res.sex || res.sex.length <= 0) {
          res.sex = 0
        }
        let sexStr = ''
        if (res.sex == '0' || res.sex == 0) {
          sexStr = '女'
          that.user_sex = 0
        } else if (res.sex == '1' || res.sex == 1) {
          sexStr = '男'
          that.user_sex = 1
        }
        if (that.user_age && that.user_age.length > 0) {
          res.birth = that.user_age
        }
        if (that.user_intro && that.user_intro.length > 0) {
          res.intro = that.user_intro
        }
        let showInApp = true
        if (res.tag && res.tag.length > 0) {
          showInApp = res.has_app == '1'
        }
        if (res.businessInfo && res.businessInfo.length > 0) {
          that.user_reply = base64.decode(res.businessInfo)
        }

        that.setData({
          userInfo: res,
          sexValue: sexStr,
          avatarurl: avatarLink,
          hasBaseInfo: res.tag.indexOf('1') >= 0,
          hasPhoto: res.tag.indexOf('2') >= 0,
          hasVideo: res.tag.indexOf('3') >= 0,
          hasApp: res.tag.indexOf('4') >= 0,
          autoReply: res.show == "1",
          isAccept: showInApp,
          businessInfo: that.user_reply
        })
        that.user_name = res.uname
        that.user_sex = res.sex
        that.user_age = res.birth
        that.user_intro = res.intro

        that.getAllUpladedImages()
        that.getAllUpladedVideos()
      }
      tt.hideLoading();
    }, reget)
  },

  //获取该用户所有已上传的图片信息
  getAllUpladedImages: function(reget = false) {
    var that = this;
    app.getAllUpladedImages(that.cuid, reget, function(res){
      if(res != 0 && res != -1) {
        that.setData({
          photoArr: res,
        })
      }
    })
  },

  //获取该用户所有已上传的视频信息
  getAllUpladedVideos: function(reget = false) {
    var that = this;
    app.getAllUpladedvideos(that.cuid, reget, function(res){
      if(res != 0 && res != -1) {
        that.setData({
          videoArr: res,
        })
      }
      tt.hideLoading();
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  onShow: function () {
    this.getLoginUserInfo();
    if(this.isReadedXieyi){
      this.acceptAction(true)
    }

    var that = this
    app.initScreenInfo(function(res){
      if(res) {
        var p_w = (app.screen_w - 50) / 3
        that.setData({
          isIphone_x: app.isIphone_x,
          screen_w: app.screen_w,
          screen_h: app.screen_h,
          info_item_w: app.screen_w - 30,
          input_w: app.screen_w - 100,
          photo_w: p_w,
          photo_h: p_w * 1.5,
          video_w: (app.screen_w - 40)/2,
          video_h: (app.screen_w - 40)/2 * 0.5625,
        });
      }
      console.log("video_w = " + that.data.video_w + "; video_h = " + that.data.video_h)  
    })
    
  },

  goAtherPage: function (e) {
    console.log("goAtherPage!!!!!!!!");
    var url = e.currentTarget.dataset.link;
    tt.navigateTo({
      url: url
    })
  },

  /**隐藏授权提示 */ 
  hideAuthView(){
    this.setData({
      showAuthView: false
    })
  },
  /**头像点击 */
  avatarClick() {
    this.setData({
      showAuthView: true
    })
  },

  /**授权获取微信用户信息 */
  authWXuserInfo(e) {
    console.log("个人信息授权：", e)
    let userInfoOb = this.data.userInfo
    userInfoOb.avatar = e.detail.userInfo.avatarUrl
    this.setData({
      userInfo: userInfoOb
    })
  },
  inputAction: function(e){
    let inputName = e.currentTarget.dataset.name
    console.log("输入：" + inputName, e)
    let inputContent = e.detail.value
    if (inputName == "userName") {//姓名输入
      this.user_name = inputContent
    } else if (inputName == "userAge") { // 年龄输入
      this.user_age = inputContent
    } else if (inputName == "userLabel") {// 个人签名输入
      this.user_intro = inputContent
    }
  },
  selectSex: function() {
    var that = this
    tt.showActionSheet({
      itemList: ['女', '男'],
      success (res) {
        console.log("选择性别", res)
        let sexStr = ''
        if (res.tapIndex == 0) {
          sexStr = '女'
          that.user_sex = 0
        } else if (res.tapIndex == 1) {
          sexStr = '男'
          that.user_sex = 1
        }
        that.setData({
          sexValue: sexStr
        })
      }
    })
  },

  autoReplyAction: function (ev) {
    let autoReply = this.data.autoReply
    this.setData({
      autoReply: !autoReply
    })
  },

  acceptAction: function(ev) {
    console.log("isReadedXieyi: ", ev)
    console.log("isReadedXieyi: ", this.isReadedXieyi)
    if(ev.type == "tap") {
      if (!this.isReadedXieyi && !this.data.isAccept) {
        tt.navigateTo({
          url: '/pages/xieyi/xieyi',
        })
      } else {
        let accept = this.data.isAccept
        this.setData({
          isAccept: !accept
        })
      }
    } else {
      this.setData({
        isAccept: true
      })
    }

  },

  replyInput: function (params) {
    
    this.user_reply = params.detail.value
    console.log("输入内容长度：", this.user_reply.length);
  },

  editUserInfo: function() {
    var that = this;
    let noGetSubMsg = app.noSubscribeMessageCache()
    console.log("已经授权订阅消息：" + noGetSubMsg)
    if (noGetSubMsg) {
      tt.requestSubscribeMessage({
        tmplIds: [app.globalData.tmplMsgIds],
        success(res) {
          console.log("订阅消息结果：", res)
          if (res.errMsg.indexOf(":ok") > 0) {
            app.setSubscribeMessageCache()
          }
        }
      })
    }
    // if(that.data.avatarurl.indexOf('http') < 0){
    //   tt.showToast({
    //     title: '请上传头像',
    //   })
    //   return
    // }
    if(that.user_name.length <= 0){
      tt.showToast({
        title: '请输入姓名',
      })
      return
    }
    if(!that.user_age || that.user_age.length <= 0){
      tt.showToast({
        title: '请输入年龄',
      })
      return
    }
    if(that.user_intro.length <= 0){
      tt.showToast({
        title: '请输入个签',
      })
      return
    }
    if (that.data.autoReply && (!that.user_reply || that.user_reply.length <= 0)) {
      tt.showToast({
        title: '请输入回复内容',
      })
      return
    }

    tt.showLoading({
      title: '...',
    })

    var newInfoTag = that.getHasInfoTag()
    let privateKey = utilMd5.hexMD5(that.cuid + "edituserinfo" + that.token);
    let firstPhotoArr = ''
    if(that.data.photoArr.length > 0){
      let photoUrl = {}
      photoUrl.url = that.data.photoArr[0].url
      firstPhotoArr = []
      firstPhotoArr = firstPhotoArr.concat(photoUrl)
    }
    let userReplyB64 = ""
    if(that.user_reply && that.user_reply.length > 0) {
      userReplyB64 = base64.encode(that.user_reply)
    }

    let commitData = {
      "privatekey": privateKey,
      "ac": "edituserinfo",
      "uid": that.cuid,
      "edituid": that.cuid,
      "nickname": that.user_name,
      "avatar": that.data.avatarurl,//头像链接
      "photo": JSON.stringify(firstPhotoArr),//相册的第一张链接
      "sex": that.user_sex,//性别
      "birth": that.user_age,//年龄
      "intro": that.user_intro,//个人签名
      "has_app": that.data.isAccept ? '1': '0', //是否展示在电视app上
      "phone": that.cuid,
      "tag": newInfoTag,
      "show": that.data.autoReply ? '1' : '0',//是否自动回复
      "businessInfo": userReplyB64, // 自动回复内容
      "usercata": that.data.isAccept ? '1': '0'
    };
    console.log("编辑用户数据参数：", commitData)

    util.api_go({
      data: commitData,
      method: "POST",
      success: function(responseData) {
        console.log(responseData);
        if (responseData.data.res) {
          //保存成功，更新本地缓存的 用户信息
          let msgCount = that.getMsgCount(newInfoTag)
          // that.getLoginUserInfo(true);
          if(msgCount > 0) {
            app.addMessageCount(msgCount, function(res){
              that.getLoginUserInfo(true)
            })
          } else {
            that.getLoginUserInfo(true);
          }
          
          that.user_name = ''
          that.user_age = ''
          that.user_intro = ''
          that.newAvatarUrl = ''

          tt.hideLoading()
          tt.showToast({
            title: '保存成功',
          })
          tt.navigateBack({
            delta: 1
          })
        } else {
          tt.showToast({
            title: responseData.data.msg,
          })
        }
      }
    });
  },

  //计算该添加的用户信息条数
  getMsgCount: function(newInfoTag) {
    let msgCount = 0
    let oldInfoTag = this.data.userInfo.tag
    if (newInfoTag.indexOf("1") >= 0 && oldInfoTag.indexOf("1") < 0) {
      msgCount += 5
    }
    if (newInfoTag.indexOf("2") >= 0 && oldInfoTag.indexOf("2") < 0) {
      msgCount += 5
    }
    if (newInfoTag.indexOf("3") >= 0 && oldInfoTag.indexOf("3") < 0) {
      msgCount += 5
    }
    if (newInfoTag.indexOf("4") >= 0 && oldInfoTag.indexOf("4") < 0) {
      msgCount += 5
    }
    console.log("msgCount = " + msgCount)
    return msgCount
  },

  //获取资料完善程度
  getHasInfoTag: function() {
    let tag = this.data.userInfo.tag
    //基本资料
    if(tag.indexOf("1") < 0 && this.user_name && this.user_name.length > 0 && this.user_age && this.user_age.length > 0
      && this.user_intro && this.user_intro.length > 0) {
        tag += "1"
    } 
    //相册
    if(tag.indexOf("2") < 0 && this.data.photoArr && this.data.photoArr.length > 0) {
      tag += "2"
    }
    //视频
    if(tag.indexOf("3") < 0 && this.data.videoArr && this.data.videoArr.length > 0) {
      tag += "3"
    }
    //是否同意展示在电视app上
    if(tag.indexOf("4") < 0 && this.data.isAccept) {
      tag += "4"
    }
    console.log("tag = " + tag)
    return tag
  },

  showToastAction: function() {
    tt.showToast({
      title: "暂不支持编辑头像",
      success: (res) => {
        
      },
      fail: (res) => {
        
      },
    });
  }

})